import React, { useMemo } from 'react'
import { Tabs, TabsProps, ConfigProvider } from 'antd'
import zh_CN from 'antd/locale/zh_CN'
import { PermissionKey, UserPermission, type User } from '../server/interface'
import { changeSearch, connect, getState, hasPermission } from './store'
import Profile from './components/Profile'
import UserList from './components/user'
import RoleList from './components/role'
import PermList from './components/perm'

interface AppProps {
    loginUser: User;
    page: string;
    perm_map: Map<string, UserPermission>;
}
const App = (props: AppProps) => {
    const { loginUser, page, perm_map } = props;
    const [items, tabKey = 'profile'] = useMemo(() => {
        const items: TabsProps['items'] = [
            {
                key: 'profile',
                label: perm_map.get(PermissionKey.RBAC_SELF)?.name || '个人中心',
                children: <Profile />
            },
        ];
        if (hasPermission(PermissionKey.RBAC_USER)) {
            items.push({
                key: 'user',
                label: perm_map.get(PermissionKey.RBAC_USER)?.name || '用户管理',
                children: <UserList />,
            })
        }
        if (hasPermission(PermissionKey.RBAC_ROLE)) {
            items.push({
                key: 'role',
                label: perm_map.get(PermissionKey.RBAC_ROLE)?.name || '角色管理',
                children: <RoleList />,
            })
        }
        if (hasPermission(PermissionKey.RBAC_PERMISSION)) {
            items.push({
                key: 'permission',
                label: perm_map.get(PermissionKey.RBAC_PERMISSION)?.name || '权限管理',
                children: <PermList />,
            })
        }
        const tabKey = items.find(t => t.key === page)?.key
        return [items, tabKey]
    }, [loginUser, page, perm_map]);

    return <ConfigProvider locale={zh_CN} >
        <div style={{ width: '90%', margin: '0 auto', maxWidth: 1200 }}>
            <Tabs items={items} activeKey={tabKey} onChange={(key) => {
                changeSearch({ page: key }, '系统管理 ' + items.find(t => t.key === key)?.label)
            }}/>
        </div>
    </ConfigProvider>
}

export default connect(() => {
    const { loginUser, location_search, perm_map } = getState()
    return { loginUser, page: location_search.get('page'), perm_map }
})(App)